package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.service.ArticleService;
import com.example.forum.service.BoardService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;
    @Resource
    private BoardService boardService;
    /**
     * 发布新帖子
     * @param boardId 板块Id
     * @param title   文章标题
     * @param content 文章内容
     * @return
     */

    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @RequestParam("boardId")@NonNull Long boardId,
                            @RequestParam("title")@NonNull String title,
                            @RequestParam("content")@NonNull String content){
        // 效验用户是否禁言
        HttpSession session = request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            //用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_EXISTS);
        }
        //板块的效验
        Board board=boardService.selectById(boardId.longValue());
        if (board==null || board.getDeleteState()==1 || board.getState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //返回响应
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);//  标题
        article.setContent(content);//  正文
        article.setBoardId(boardId);//  板块ID
        article.setUserId(user.getId());//  作者id
        //调用Service
        articleService.create(article);
        //响应
        return  AppResult.success();
    }
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId (@RequestParam(value = "boardId", required = false) Long boardId) {

        // 定义返回的集合
        List<Article> articles ;
        // 判断传入的参数是否为空
        if (boardId == null) {
            // 如果传入的参数为空，查询所有
            articles = articleService.selectAll();
        } else {
            // 如果传入的版块Id不为空，查询指定版块下的帖子列表
            articles = articleService.selectAllByBoardId(boardId);
        }

        // 结果是否为空
        if (articles == null) {
            // 如果结合集为空，那么创建上个空集合
            articles = new ArrayList<>();
        }
        // 响应结果
        return AppResult.success(articles);
    }

    @GetMapping("/details")
    public  AppResult<Article> getDetails(HttpServletRequest request,
                                          @RequestParam(value = "id", required = false) Long id){
        //从session中获取当前登录的的用户
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用Service，获取忒子详情
        Article article = articleService.selectDetailById(id);
        //判断结果是否为空
        if (article==null){
            //返回错误信息
            return  AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS.getMessage());
        }
        //判断当前用户是否为作者
        if (user.getId()==article.getUserId()){
            //标识为作者
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }
//    @GetMapping("modify")
//    public AppResult modify(HttpServletRequest request,
//                            @RequestParam(value = "id") @NonNull Long id,
//                            @RequestParam(value = "title") @NonNull String title,
//                            @RequestParam(value = "content") @NonNull String content){
//
////      获取当前登录的用户
//        HttpSession session= request.getSession(false);
//        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
//        // 体验用户状态
//        if (user.getState()==1){
//            // 返回错误描述
//            return  AppResult.failed(ResultCode.FAILED_USER_BANNED);
//        }
//        // 查询帖子详情
//        Article article=articleService.selectById(id);
//        // 检验忒子是否有效
//        if (article==null){
//            //返回错误描述
//            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
//        }
//        // 判断用户是否是作者
//        if (user.getId()!=article.getUserId()){
//            // 返回错误描述
//            return  AppResult.failed(ResultCode.FAILED_FORBIDDEN);
//        }
//        // 判断帖子的状态 - 已归档
//        if (article.getState()==1){
//            //返回错误描述
//            return  AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
//        }
//
//        // 带哦用Service
//        articleService.modify(id,title,content);
//        // 打印日志
//        log.info("帖子更新成功，Article id= "+id+"User id= "+user.getId()+"。");
//        //返回正确结果
//        return AppResult.success();
//
//    }
    @PostMapping("/modify")
    public AppResult modify (HttpServletRequest request,
                             @RequestParam("id") @NonNull Long id,
                             @RequestParam("title") @NonNull String title,
                             @RequestParam("content") @NonNull String content) {
        // 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 校验用户状态
        if (user.getState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子是否有效
        if (article == null) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断用户是不是作者
        if (user.getId() != article.getUserId()) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 判断帖子的状态 - 已归档
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 调用Service
        articleService.modify(id, title, content);
        // 打印日志
        log.info("帖子更新成功. Article id = " + id + "User id = " + user.getId() + ".");
        // 返回正确的结果
        return AppResult.success();
    }

    @RequestMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @RequestParam("id") @NonNull Long id){
        // 效验用户的状态
        HttpSession session=request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if (user.getState()==1){
            // 返回结果
            return  AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 直接调用service
        articleService.thumbsUpById(id);
        //
        return AppResult.success();
    }

    @RequestMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @RequestParam("id") @NonNull Long id){

        //效验用户状态
        HttpSession session = request.getSession(false);
        User user=(User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            //表示用户禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 效验帖子状态
        if (article==null|| article.getDeleteState()==1){
            // 帖子已删除
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //效验当前登录的用户是不是作者
        if (user.getId()!=article.getUserId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调用service
        articleService.deleteById(id);
        // 返回成功成功
        return AppResult.success();
    }

    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                                    @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null) {
            // 获取Session
            HttpSession session = request.getSession(false);
            // 获取User对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用Service
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }
}
